package org.oak.filter;

/**
 * org.oak.filter.LoggingFilter
 *
 * @author ZRS
 * @version V1.0
 * @since 2025/10/30 18:02
 */

import javax.servlet.*;
import java.io.IOException;

public class LoggingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取初始化参数
        String logLevel = filterConfig.getInitParameter("logLevel");
        System.out.println("LoggingFilter initialized with logLevel: " + logLevel);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 1. 请求预处理
        long startTime = System.currentTimeMillis();
        System.out.println("Request received at: " + startTime);

        try {
            // 2. 调用后续的Filter或目标资源
            chain.doFilter(request, response);
        } catch (Exception e) {
            // 异常处理
            System.err.println("Error in filter chain: " + e.getMessage());
            throw e;
        } finally {
            // 3. 响应后处理
            long endTime = System.currentTimeMillis();
            System.out.println("Request processed in: " + (endTime - startTime) + "ms");
        }
    }

    @Override
    public void destroy() {
        System.out.println("LoggingFilter destroyed");
    }
}